package io.lvdaxian.mybatis07.session.defaults;

import io.lvdaxian.mybatis07.executor.Executor;
import io.lvdaxian.mybatis07.mapping.MappedStatement;
import io.lvdaxian.mybatis07.session.Configuration;
import io.lvdaxian.mybatis07.session.SqlSession;

/**
 * DefaultSqlSession 是对象接口【SqlSession】的实现
 *
 * @author lihh
 */
public class DefaultSqlSession implements SqlSession {
  
  // 表示 控制上下文的配置文件
  private final Configuration configuration;
  // 执行器
  private final Executor executor;
  
  public DefaultSqlSession(Configuration configuration, Executor executor) {
    this.configuration = configuration;
    this.executor = executor;
  }
  
  @Override
  public <T> T selectOne(String statement) {
    return (T) ("你被代理了！" + "方法：" + statement);
  }
  
  /**
   * 根据 statement 找到对应的sql，以及 通过参数【parameter】查询数据
   *
   * @param statement 能查询到对应sql的唯一id
   * @param parameter 实现的动态参数
   * @param <T>       动态泛型
   * @return 返回响应的值
   * @author lihh
   */
  @Override
  public <T> T selectOne(String statement, Object parameter) {
    // 拿到 mappedStatement 语句
    MappedStatement ms = configuration.getMappedStatement(statement);
    // 因为这里是 selectOne 操作，所以只能获取一个数据
    return (T) executor.query(ms, parameter, Executor.NO_RESULT_HANDLER, ms.getBoundSql()).get(0);
  }
  
  
  @Override
  public <T> T getMapper(Class<T> clazz) {
    return configuration.getMapper(clazz, this);
  }
  
  @Override
  public Configuration getConfiguration() {
    return configuration;
  }
}
